package initialize

import (
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"gitee.com/baal1990/epidemic/global"
	"gitee.com/baal1990/epidemic/utils/crypto"
	"go.uber.org/zap"
	"io/ioutil"
	"os"
)

// 初始化对称加密工具
func InitAsymmetricCrypto(prvKeyFilePath, pubKeyFilePath string) {
	pkFile, err := os.Open(pubKeyFilePath)
	if err != nil {
		zap.S().Fatal("打开公钥文件失败", zap.Error(err))
	}

	pkBytes, err := ioutil.ReadAll(pkFile)
	if err != nil {
		zap.S().Fatal("读取公钥文件失败", zap.Error(err))
	}
	pkFile.Close()
	block, _ := pem.Decode(pkBytes)
	pubKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		zap.S().Fatal("转换公钥失败", zap.Error(err))
	}
	pubKey := pubKeyInterface.(*rsa.PublicKey)

	prvFile, err := os.Open(prvKeyFilePath)
	if err != nil {
		zap.S().Fatal("打开私钥文件失败", zap.Error(err))
	}

	prvBytes, err := ioutil.ReadAll(prvFile)
	if err != nil {
		zap.S().Fatal("读取私钥文件失败", zap.Error(err))
	}
	prvFile.Close()
	block, _ = pem.Decode(prvBytes)
	prvKeyInterface, err := x509.ParsePKCS8PrivateKey(block.Bytes)
	if err != nil {
		zap.S().Fatal("转化私钥失败", zap.Error(err))
	}
	prvKey := prvKeyInterface.(*rsa.PrivateKey)

	global.AsymmetricCrypto = crypto.NewRSACrypto(pubKey, prvKey)
}

// 初始化对称加密工具
func InitSymmetricCrypto() {
	global.SymmetricCrypto = crypto.NewAESCrypto([]byte(global.ENCRYPTKEY_AES))
	global.Rc4Crypto = crypto.NewRC4Crypto([]byte(global.ENCRYPTKEY_RC4))
}

func InitCrypto(prvKeyFilePath, pubKeyFilePath string) {
	InitAsymmetricCrypto(prvKeyFilePath, pubKeyFilePath)
	InitSymmetricCrypto()
}
